#!/bin/bash
#本文件用于设置锚节点

#imports
. scripts/utils.sh
. scripts/envVar.sh

CHANNEL="channel2"

#此函数需要在CLI中执行
createAnchorPeerUpdate() {
    infoln "Fetching channel config for channel2"
    #fetchChannelConfig ${CORE_PEER_LOCALMSPID}config.json

    setGlobals 3

    infoln "Fetching the most recent configuration block for the channelc"
    set -x
    peer channel fetch config config_block.pb -o orderer.project.com:7050 --ordererTLSHostnameOverride orderer.project.com -c $CHANNEL --tls --cafile "$ORDERER_CA"
    { set +x; } 2>/dev/null

    infoln "Decoding config block to JSON and isolating config to ${CORE_PEER_LOCALMSPID}config.json"
    set -x
    configtxlator proto_decode --input config_block.pb --type common.Block --output config_block.json
    jq .data.data[0].payload.data.config config_block.json >"${CORE_PEER_LOCALMSPID}config.json"
    { set +x; } 2>/dev/null

    infoln "Generating anchor peer update transaction for Org3 on channel $CHANNEL"
    
    HOST="peer0.org3.project.com"
    PORT=7060

    set -x
    #修改配置文件使其增加配置锚节点的部分
    jq '.channel_group.groups.Application.groups.'${CORE_PEER_LOCALMSPID}'.values += {"AnchorPeers":{"mod_policy": "Admins","value":{"anchor_peers": [{"host": "'$HOST'","port": '$PORT'}]},"version": "0"}}' ${CORE_PEER_LOCALMSPID}config.json > ${CORE_PEER_LOCALMSPID}modified_config.json
    { set +x; } 2>/dev/null

    #使用configtxlator计算出设置锚节点前后的区块差值(以pb后缀表示)
    #将差值再转换为json文件，加入一些必要头部后生成一笔交易
    #这笔交易就是更新通道锚节点配置的交易
    ORIGINAL=${CORE_PEER_LOCALMSPID}config.json
    MODIFIED=${CORE_PEER_LOCALMSPID}modified_config.json
    OUTPUT=${CORE_PEER_LOCALMSPID}anchors.tx

    set -x
    configtxlator proto_encode --input "${ORIGINAL}" --type common.Config --output original_config.pb
    configtxlator proto_encode --input "${MODIFIED}" --type common.Config --output modified_config.pb
    configtxlator compute_update --channel_id "${CHANNEL}" --original original_config.pb --updated modified_config.pb --output config_update.pb
    configtxlator proto_decode --input config_update.pb --type common.ConfigUpdate --output config_update.json
    echo '{"payload":{"header":{"channel_header":{"channel_id":"'$CHANNEL'", "type":2}},"data":{"config_update":'$(cat config_update.json)'}}}' | jq . >config_update_in_envelope.json
    configtxlator proto_encode --input config_update_in_envelope.json --type common.Envelope --output "${OUTPUT}"
    { set +x; } 2>/dev/null
}

updateAnchorPeer() {
    setGlobals 3
    
    peer channel update -o orderer.project.com:7050 --ordererTLSHostnameOverride orderer.project.com -c $CHANNEL -f ${CORE_PEER_LOCALMSPID}anchors.tx --tls --cafile "$ORDERER_CA" >&log.txt
    res=$?
    cat log.txt
    verifyResult $res "Anchor peer update failed"
    successln "Anchor peer set for org '$CORE_PEER_LOCALMSPID' on channel '$CHANNEL'"
}

createAnchorPeerUpdate 

updateAnchorPeer